// Login JS Document
require.config({
    baseUrl: '/js/common', 
    paths: {
        libs: '/js/libs'
    }
});
define(function(require){
	// 加载js
	var rs_zepto = require('libs/zepto');
	var rs_yingSoftCookie = require('yingSoftCookie');
	var rs_yingSoftPrg = require('yingSoftPrg');
	var rs_agentInfo = require('agentInfo');
	var rs_ajax = require('ajax');
	var rs_md5 = require('md5');
	var rs_dialog = require('dialog');
	var rs_storage = require('storage');
	// 初始化
	var _isClick = true;	// 防止多次点击
	this.init = function(){
		var free = G_Prg.getQueryString('type');
		var free1 = G_Prg.getQueryString('liu');
//		if(free){
//			$('.backIco').css('display','block');
//		}
		var userName = G_Cookie.getUserName();
        var userPwd = G_Cookie.getUserPwd();
        if (userName&&userName.indexOf('ks')==-1) {
        // 	if(free || free1){
        // 		$('.loginUl input[type=text]').val();
        // 	}else{
        		$('.loginUl input[type=text]').val(userName);
        	// }
            if (userPwd) {
                var pwdArr = userPwd.split(',');
                $('.loginUl input[type=password]').val(pwdArr[0].substring(0, Number(pwdArr[1])));
            }
        }
        _immediatelyCheckName();
        // 加载点击事件
        _setClickEven();

        function _immediatelyCheckName() {
            var element = $('.loginUl input[type=text]');
            if ("\v" === "v") {
                element.onpropertychange = webChange;
            } else {
                element.keyup(webChange, false);
            }
            function webChange() {
                $('.loginUl input[type=password]').val('');
                $('.prompt').html('');
            }
        }
	}
     /********************************************************************************
     函数名：_setClickEven
     功能：点击和失焦事件
     *******************************************************************************/
     function _setClickEven(){
     	$('.loginUl input[type=text]').blur(function(){
			_checkUserName();
		});
        $('.loginUl input[type=password]').blur(function () {
            _checkPwd();
        });
        $('.loginForm .button_login').click(function () {
            if(_isClick){
                $('.loadingDiv,.loadingDrop').show();
                _login();
            }
        });
     }
     /********************************************************************************
     函数名：_login
     功能：登录
     *******************************************************************************/
     function _login() {
        _isClick = false;
        var userName = $('.loginUl input[type=text]').val();
        if (!_checkUserName()) {
            _isClick = true;
            $('.loadingDiv,.loadingDrop').hide();
            return;
        }
        var loginType = 1;
        if (G_Prg.checkEmail(userName)) {
            loginType = 2;
        }
        if (G_Prg.checkCellPhone(userName)) {
            loginType = 3;
        }

        var userPassword = $('.loginUl input[type=password]').val();
        var cookiePwd = G_Cookie.getUserPwd();
        var userPasswordMd5 = '';
        var pwdArr = null;
        if (cookiePwd) {
            pwdArr = cookiePwd.split(',');
        }
        if (cookiePwd && pwdArr && userPassword === pwdArr[0].substring(0, Number(pwdArr[1]))) {//如果记录了密码
            userPasswordMd5 = pwdArr[0];
        } else {
            if (!_checkPwd()) {
                _isClick = true;
                $('.loadingDiv,.loadingDrop').hide();
                return;
            }
            userPasswordMd5 = hex_md5(userPassword);
        }
        var _success = function (json) {
            if (!json) {
                G_Prg.throw('程序运行错误，服务端无返回数据');
                _isClick = true;
                $('.loadingDiv,.loadingDrop').hide();
            }
            var jsonData = JSON.parse(json);
            if (jsonData.status === 200) {
                $('.loadingDiv,.loadingDrop').hide();
                G_Prg.cleanCookie();
                G_Cookie.setUserID(jsonData.data.userID);
                G_Cookie.setUserName(userName);
                G_Cookie.setGuid(jsonData.data.guid);
                G_Prg.setCookie('NICKNAME', jsonData.data.NickName);
                G_Cookie.setUserPwd(userPasswordMd5 + ',' + userPassword.length);
                _loginSuccess(jsonData);
            } else if (jsonData.status === 201) {
                _isClick = true;
                $('.loadingDiv,.loadingDrop').hide();
                window.scrollTo(0, 0);
                G_Prg.confirm('用户名或者密码不正确');
                $('.loginUl input[type=password]').val('');
            } else if (jsonData.status === 300) {
                _isClick = true;
                $('.loadingDiv,.loadingDrop').hide();
                window.scrollTo(0, 0);
                G_Prg.throw('程序运行错误，数据库获取数据异常');
            } else if (jsonData.status >= 400 && jsonData.status < 500) {
                _isClick = true;
                $('.loadingDiv,.loadingDrop').hide();
            } else {
                _isClick = true;
                $('.loadingDiv,.loadingDrop').hide();
                window.scrollTo(0, 0);
                G_Prg.throw('抱歉，不能处理 ，' + jsonData.status + '"！');
            }
        }
        var agentCode = G_AgentInfo.getAgentCode();
        var URL = '/api/user/login/' + userName + '/' + userPasswordMd5 + '/' + loginType + '/' + _getClientType() + '/' + _getUserAgent();
        G_AjaxApi_Record.get(URL, true, _success);
    }
    /********************************************************************************
     函数名：_loginSuccess
     功能：用户登陆成功后执行的函数
     *******************************************************************************/
    function _loginSuccess(jsonData) {
        if (G_Cookie.getLoginURL()) {
            if (!G_Cookie.getAppID() && !G_Cookie.getAppName() && !G_Cookie.getAppEName() && jsonData.data.appID && jsonData.data.appEName && jsonData.data.appName) {
                if(jsonData.data.appEName.indexOf('GJZC_') === 0&&jsonData.data.appEName.indexOf('TX',jsonData.data.appEName.length-2) === -1){
                    G_Cookie.setSelectedApp(jsonData.data.appName, jsonData.data.appEName, jsonData.data.appID);
                    // window.location.href = G_Cookie.getLoginURL();
                    // G_Cookie.removeLoginURL();
                    // return;
                }
                else{
                	G_Prg.removeCookie('freeTry');
                    window.location.href = '/switchMenu';
                    return;
                }
            }
            window.location.href = G_Cookie.getLoginURL();
            G_Cookie.removeLoginURL();
            return;
        }
        if (!G_Cookie.getAppID() && !G_Cookie.getAppName() && !G_Cookie.getAppEName() && jsonData.data.appID && jsonData.data.appEName && jsonData.data.appName) {
            if(jsonData.data.appEName.indexOf('GJZC_') === 0&&jsonData.data.appEName.indexOf('TX',jsonData.data.appEName.length-2) === -1){
                G_Cookie.setSelectedApp(jsonData.data.appName, jsonData.data.appEName, jsonData.data.appID);
                if (G_Storage.checkSessionStorageSupport) {
                    G_Storage.removeSessionStorageValue('firstLoad');
                }
                if (G_Storage.checkSessionStorageSupport) {
                    G_Storage.removeSessionStorageValue('showTime');
                }
                window.location.href = '/doExam-index';
                return;
            }
            else{
                window.location.href = '/switchMenu';
                return;
            }
        }
        if (!G_Cookie.getAppName() && jsonData.data.isVip === false) {
            window.location.href = '/switchMenu';
            return;
        }
    }
    /********************************************************************************
     函数名：_checkUserName
     功能：检查用户名是否输入的函数
     *******************************************************************************/
    function _checkUserName() {
        var userName = $('.loginUl input[type=text]').val();
        if (!userName) {
            $('.prompt').show().html('*请输入您的手机号码');
            return false;
        }
        $('.prompt').hide();
        return true;
    }
    /********************************************************************************
     函数名：_checkPwd
     功能：检查密码是否输入的函数
     *******************************************************************************/
    function _checkPwd() {
        var userPassword = $('.loginUl input[type=password]').val();
        if (!userPassword) {
            $('.prompt').show().html('*请输入您的密码');
            return false;
        }
        $('.prompt').hide();
        return true;
    }
    /********************************************************************************
     函数名：_getClientType
     功能：获取用户终端版本信息
     *******************************************************************************/
    function _getClientType() {
        var browser = {
            versions: function () {
                var u = navigator.userAgent,
                    app = navigator.appVersion;
                return {
                    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
                    android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
                    iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1,
                    iPad: u.indexOf('iPad') > -1,
                    webApp: u.indexOf('Safari') == -1
                };
            }()
        };
        if (browser.versions.iPhone || browser.versions.iPad) {
            return 'web_iPhone';
        }
        if (browser.versions.ios || browser.versions.android || browser.versions.webApp) {
            return 'web_android';
        }
        return 'web_pc';
    }
    function _getUserAgent() {
        var userAgent = navigator.userAgent.split('/');
        return userAgent;
    }
    // 执行初始化
	init();
});